package com.prdiot.poetry.controller;

import com.alibaba.fastjson.JSON;
import com.prdiot.poetry.dao.PoemsRepository;
import com.prdiot.poetry.domains.Author;
import com.prdiot.poetry.domains.Chengyu;
import com.prdiot.poetry.domains.Mingju;
import com.prdiot.poetry.domains.Poems;
import com.prdiot.poetry.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v1")
public class ApiRestController {

    @Autowired
    TagsService tagsService;

    @Autowired
    AuthorService authorService;

    @Autowired
    PoemsService poemsService;

    @Autowired
    MingjuService mingjuService;

    @Autowired
    ChengyuService chengyuService;

    @Autowired
    PoemsRepository poemsRepository;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    SearchService searchService;

    @GetMapping("/tags")
    public String tags(){
        // 获取标签列表
        return JSON.toJSONString(tagsService.getTagsOrderByPoemCount());
    }

    // 获取诗人列表
    @GetMapping("/authors/list/{page}")
    public String authors(@PathVariable(name = "page") Integer page){
        int curPage = 1;
        try{
            curPage = Math.abs(page);
            if (curPage<1){
                curPage = 1;
            }
        } catch (Exception exception){
            curPage = 1;
        }

        Page<Author> allAuthors = authorService.getAllAuthors(curPage);
        List<Author> authorList = allAuthors.getContent();
        for (Author author:authorList) {
            author.setDynastyId(poemsService.getDynastyIdByName(author.getDynasty()));
        }

        return JSON.toJSONString(allAuthors);
    }

    // 获取单个诗人信息
    @GetMapping("/authors/info/{authorId}")
    public String author(@PathVariable("authorId") String authorId){
        Author author = authorService.findByAuthorId(authorId);
        if (author != null){
            author.setDynastyId(poemsService.getDynastyIdByName(author.getDynasty()));
        }
        return JSON.toJSONString(author);
    }

    // 古诗词列表
    @GetMapping("/poem/list/{page}")
    public String poems(@PathVariable("page") String page){
        int curPage = 1;
        try{
            curPage = Math.abs(Integer.valueOf(page));
        }catch (Exception exception){
            curPage = 1;
        }

        Sort sort = new Sort(Sort.Direction.ASC, "code");
        Pageable pageable = PageRequest.of(curPage - 1, 10, sort);
        return JSON.toJSONString(poemsRepository.searchByKey("", pageable));
    }

    // 古诗词信息
    @GetMapping("/poem/info/{id}")
    public String poemInfo(@PathVariable("id") String id){
        Poems poems = poemsService.searchPoemsByCode(id);
        return JSON.toJSONString(poems);
    }

    // 成语列表
    @GetMapping("/chengyu/list/{page}")
    public String index(@PathVariable("page") String page){

        int curPage = 1;
        try{
            curPage = Math.abs(Integer.valueOf(page));
        }catch (Exception exception){
            curPage = 1;
        }
        int pageCount = 0;

        Sort sort = new Sort(Sort.Direction.ASC, "code");
        Pageable pageable = PageRequest.of(curPage - 1, 10, sort);
        return JSON.toJSONString(chengyuService.getChengyuList(pageable));
    }

    // 单个名句信息
    @GetMapping("/chengyu/info/{code}")
    public String findChengyu(@PathVariable("id") String code){
        Chengyu chengyu = chengyuService.findByCode(code);
        return JSON.toJSONString(chengyu);
    }


    //名句列表
    @GetMapping("/mingju/list/{page}")
    public String mingjuList(@PathVariable("page") String page){

        int curPage = 1;
        try{
            curPage = Math.abs(Integer.valueOf(page));
        }catch (Exception exception){
            curPage = 1;
        }
        int pageCount = 0;

        Sort sort = new Sort(Sort.Direction.ASC, "code");
        Pageable pageable = PageRequest.of(curPage - 1, 10, sort);

        return JSON.toJSONString(mingjuService.getMingjuList(pageable));
    }

    // 名句信息
    @GetMapping("/mingju/info/{id}")
    public String findMingju(@PathVariable("id") String id){
        Mingju mingju = mingjuService.findByCode(id);
        return JSON.toJSONString(mingju);
    }

    //获取译注赏内容
    @GetMapping("/ext/{type}/{poemid}")
    public String getPoemExt(@PathVariable("type") String type, @PathVariable("poemid") String poemid){
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(poemid)){
            return "none";
        }else{
            Map<String, Object> poemExt =  poemsService.getPoetryExt(poemid);

            Context context = new Context();
            context.setVariable("body", poemExt.get("body"));

            if (type.contains("yi")){
                context.setVariable("trans", poemExt.get("trans"));
                context.setVariable("transRel", poemExt.get("transRel"));
            }
            if (type.contains("zhu")){
                context.setVariable("expl", poemExt.get("expl"));
            }
            if (type.contains("shang")){
                context.setVariable("shang", poemExt.get("shang"));
            }
            String result = templateEngine.process("poemExt", context);
            return result;
        }
    }

    //搜索功能
    @GetMapping("/search/{type}/{key}/{page}")
    public Map<String,Object>  search(@PathVariable("type") String type,@PathVariable("key") String key,
                         @PathVariable("page") int page){
        if (page<1){
            page = 1;
        }
        if (StringUtils.isEmpty(type)){
            type = "poem";
        }

        Map<String, Object> mapResult = searchService.search(page,key,type);
        Map<String,Object> result = new HashMap<>();
        result.put("data", mapResult.get("list"));
        result.put("page", Integer.valueOf(page));
        result.put("pageCount",  Integer.valueOf(mapResult.get("pageCount").toString()));
        result.put("searchType", type);
        result.put("searchVal", key);
        if (type.equalsIgnoreCase("author")){
            result.put("extPomesData", mapResult.get("extPomesData"));
        }
        return result;
    }

    // 按照类别检索诗词
    @GetMapping("/poems/{type}/{key}/{page}")
    public Map<String,Object> poems(@PathVariable("type") String type,@PathVariable("key") String key,
                        @PathVariable("page") int page){

        if(page < 1){
            page = 1;
        }
        int pageCount = 0;
        Sort sort = new Sort(Sort.Direction.ASC, "code");
        Pageable pageable = PageRequest.of(page - 1, 10, sort);
        Page<Poems> poemsPage = null;
        if (type.equals("tag")){
            poemsPage = poemsService.searchPoemsByTag(key,pageable);
        }else if (type.equals("author")){
            poemsPage = poemsService.searchPoemsByAuthorId(key,pageable);
        }else if (type.equals("dynasty")){
            poemsPage = poemsService.searchPoemsByDynastyId(key,pageable);
        }else if (type.equals("type")){
            poemsPage = poemsService.searchPoemsByType(key,pageable);
        }
        List<Poems> list = null;
        if (poemsPage == null){
            list = new ArrayList<>();
            pageCount = 0;
        }else{
            list = poemsService.attachTag(poemsPage.getContent());
            pageCount = poemsPage.getTotalPages();
        }
        Map<String,Object> result = new HashMap<>();
        result.put("data", list);
        result.put("page", page);
        result.put("pageCount", pageCount);
        result.put("key", key);
        result.put("type", type);
        return result;
    }

}
